package com.ukao.steward.ui.valetRunners.waitingOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.steward.R;
import com.ukao.steward.adapter.ClothingListAdapter;
import com.ukao.steward.adapter.PayListAdapter;
import com.ukao.steward.adapter.StorageClothingListAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.OrderDetailBean;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.bean.ProductListBean;
import com.ukao.steward.bean.ReceiptBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.bean.TradeOrderBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.dialog.TransNoDialogFragment;
import com.ukao.steward.eventbus.PayEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.pesenter.valetRunners.OrderdetailPesenter;
import com.ukao.steward.printer.BluetoothPrintHelper;
import com.ukao.steward.printer.PrintMiuiHelper;
import com.ukao.steward.ui.main.HomeFragment;
import com.ukao.steward.ui.main.MainActivity;
import com.ukao.steward.ui.valetRunners.createOrder.EasyOrederFragment;
import com.ukao.steward.ui.valetRunners.createOrder.PayOrderFragment;
import com.ukao.steward.ui.valetRunners.createOrder.shoppingMallFragment;
import com.ukao.steward.ui.valetRunners.storage.StorageListFragment;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DecimalUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.OrderdetailView;
import com.ukao.steward.widget.StateButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.bottom_layout;
import static com.ukao.steward.R.id.gather_btn;
import static com.ukao.steward.R.id.precise_compute_btn;
import static com.ukao.steward.R.id.receipt_btn;


/**
 * 订单详情
 */
public class OrderdetailFragment extends MvpFragment<OrderdetailPesenter> implements OrderdetailView{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.orderNo)
    TextView orderNo;
    @BindView(R.id.business)
    TextView business;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.storge_recycler_view)
    RecyclerView storgeRecyclerView;
    @BindView(R.id.total_amount)
    TextView totalAmount;
    @BindView(R.id.un_total_layout)
    LinearLayout unTotalLayout;
    @BindView(R.id.takeSend_price)
    TextView takeSendPrice;
    @BindView(R.id.userRemark)
    TextView userRemark;

    @BindView(R.id.pay_state_hite)
    TextView payStateHite;
    @BindView(R.id.pay_state)
    TextView payState;
    @BindView(R.id.PaymentPrice)
    TextView PaymentPrice;
    @BindView(R.id.compute_count)
    TextView computeCount;

    @BindView(R.id.compute_pice)
    TextView computePice;

    @BindView(R.id.should_price)
    TextView shouldPrice;


    @BindView(R.id.pay_recycler_view)
    RecyclerView payRecyclerView;
    @BindView(R.id.pay_layout)
    LinearLayout payLayout;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.compute_top)
    View computeTop;
    @BindView(R.id.textView2)
    TextView textView2;

    @BindView(R.id.compute_bottom)
    View computeBottom;
    @BindView(R.id.textView6)
    TextView textView6;

    @BindView(R.id.couponAmt)
    TextView couponAmt;
    @BindView(receipt_btn)
    TextView receiptBtn;

    @BindView(R.id.compute_layout)
    LinearLayout computeLayout;
    @BindView(gather_btn)
    StateButton gatherBtn;
    @BindView(R.id.signin_btn)
    StateButton signinBtn;

    @BindView(R.id.gather_btn_layout)
    LinearLayout gatherBtnLayout;
    @BindView(precise_compute_btn)
    StateButton preciseComputeBtn;
    @BindView(R.id.enter_strong_txt)
    TextView enterStrongTxt;
    @BindView(R.id.create_order_txt)
    TextView createOrderTxt;
    @BindView(R.id.transNo)
    TextView transNo;
    @BindView(R.id.transNo_btn)
    StateButton transNoBtn;
    @BindView(bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R.id.bottom_line)
    View bottomLine;
    @BindView(R.id.takeName)
    TextView takeNametxt;
    @BindView(R.id.takeAddress)
    TextView takeAddress;
    @BindView(R.id.textView8)
    TextView textView8;
    @BindView(R.id.isEnableStockIn_btn)
    StateButton isEnableStockInBtn;
    @BindView(R.id.call_phone_image)
    ImageView callPhoneImage;



    private List<TradeOrderBean.ListBean> mTradeOrderData = new ArrayList<>();
    private List<StringBean> mData = new ArrayList<>();
    private List<ProductListBean> mstorgeData = new ArrayList<>();


    private ClothingListAdapter mClothingListAdapter;
    private ArrayList<StringBean> mClothlist;

    private PayListAdapter mPayListAdapter;
    private StorageClothingListAdapter mStorageClothingAdapter;
    private OrderDetailBean mOrderDetailBean;

    private String clototalAmount;


    private boolean isValuation;
    private String takeName;
    private String takephone;
    private ProductListBean mItem;
    private boolean isCreateOrderEnter;
    private String orderId;
    private boolean isEndledSign;
    private boolean isPopToHome;


    public static Builder createBuilder(
    ) {
        return new Builder();
    }
    public static  class Builder {
        private boolean isValuation;
        private String takeName;
        private String takephone;

        private boolean isCreateOrderEnter;
        private String orderId;
        private boolean isEndledSign;
        private  boolean  isPopToHome;
        public Builder() {


        }


        public Builder isPopToHome(boolean val) {
            isPopToHome = val;
            return this;
        }

        public Builder isValuation(boolean val) {
            isValuation = val;
            return this;
        }

        public Builder takeName(String val) {
            takeName = val;
            return this;
        }

        public Builder takephone(String val) {
            takephone = val;
            return this;
        }

        public Builder isEndledSign(boolean val) {

            isEndledSign= val;
            return this;
        }
        public Builder isCreateOrderEnter(boolean val) {
            isCreateOrderEnter = val;
            return this;
        }



        public  Builder orderId(String val) {
            orderId = val;
            return this;
        }

        public OrderdetailFragment build() {
            OrderdetailFragment fragment = new OrderdetailFragment();
            Bundle args = new Bundle();
            args.putString("orderId", orderId);
            args.putBoolean("isValuation", isValuation);
            args.putString("takeName", takeName);
            args.putString("takephone", takephone);
            args.putBoolean("isCreateOrderEnter", isCreateOrderEnter);
            args.putBoolean("isEndledSign", isEndledSign);
            args.putBoolean("isPopToHome", isPopToHome);
            fragment.setArguments(args);

            return fragment;
        }
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId = getArguments().getString("orderId");
            takeName = getArguments().getString("takeName");
            takephone = getArguments().getString("takephone");
            isPopToHome = getArguments().getBoolean("isPopToHome", false);
            isValuation = getArguments().getBoolean("isValuation", false);
            isCreateOrderEnter = getArguments().getBoolean("isCreateOrderEnter", false);
            isEndledSign= getArguments().getBoolean("isEndledSign", false);
        }
    }




    @Override
    protected OrderdetailPesenter createPresenter() {
        return new OrderdetailPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_orderdetail, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }


    @Override
    protected void initView() {


        setStatusBarTintColor(R.color.normal_blue);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("订单详情");
        initLinearRecyclerView(recyclerView);
        mClothingListAdapter = new ClothingListAdapter(_mActivity, mData);
        recyclerView.setAdapter(mClothingListAdapter);

        initLinearRecyclerView(storgeRecyclerView);
        mStorageClothingAdapter = new StorageClothingListAdapter(_mActivity, mstorgeData);
        storgeRecyclerView.setAdapter(mStorageClothingAdapter);


        initLinearRecyclerView(payRecyclerView);
        mPayListAdapter = new PayListAdapter(_mActivity, mTradeOrderData);
        payRecyclerView.setAdapter(mPayListAdapter);
        mvpPresenter.orderDetail(orderId);

        payRecyclerView.setNestedScrollingEnabled(false);
        recyclerView.setNestedScrollingEnabled(false);
        storgeRecyclerView.setNestedScrollingEnabled(false);


    }


    @Override
    protected void initListener() {
        super.initListener();
        mStorageClothingAdapter.setOnItemChildClickListener((id, pos, item) -> {
             mItem= (ProductListBean) item;
            TransNoDialogFragment.createBuilder(getChildFragmentManager())
                    .clothingId(mItem.getId())
                    .mTitle(getString(R.string.tie_the))
                    .isAddTransNo(false)
                    .EditTextHide(getString(R.string.please_enter_tag_number))
                    .error(getString(R.string.tag_number))
                    .mListener(mDialogSubmitListener)
                    .show();
        });

    }



    private void fillData(OrderDetailBean mOrderDetailBean) {
        mvpPresenter.orderProductList(orderId);
        scrollView.setVisibility(View.VISIBLE);
        this.mOrderDetailBean = mOrderDetailBean;
        orderNo.setText(CheckUtils.isEmptyString(mOrderDetailBean.getOrderNo()));
        String strBusiness = mOrderDetailBean.getBusiness();  /*服务项目*/
        Gson mGson = new Gson();
        String serve = "";
        if (!CheckUtils.isEmpty(strBusiness)) {  /*/*服务项目*/
            List<StringBean> mColorDesclist = mGson.fromJson(strBusiness,
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            StringBuffer mServeBuffer = new StringBuffer();
            for (int i = 0; i < mColorDesclist.size(); i++) {
                if (i != mColorDesclist.size() - 1) {
                    mServeBuffer.append(mColorDesclist.get(i).getName() + "/");
                } else {
                    mServeBuffer.append(mColorDesclist.get(i).getName());
                }


            }
            serve = mServeBuffer.toString();
        }

        if (!CheckUtils.isEmpty(mOrderDetailBean.getProPriceDesc())) {  /*衣物列表*/
            createOrderTxt.setVisibility(View.VISIBLE);
            mClothlist = mGson.fromJson(mOrderDetailBean.getProPriceDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());

            mClothingListAdapter.setDataList(mClothlist);
            mOrderDetailBean.setmClothlist(mClothlist);

        }

        if ( mOrderDetailBean.isIsEnablePrint()) {
            receiptBtn.setVisibility(View.VISIBLE);
        }
        String   namePhone;
        String phone = mOrderDetailBean.getTakePhone();
        if (!mOrderDetailBean.getTakePhone().isEmpty()){
            namePhone=mOrderDetailBean.getTakePhone()+"  "+mOrderDetailBean.getTakeName();
        }else{
            namePhone=mOrderDetailBean.getTakeName();
        }

        callPhoneImage.setVisibility(!CheckUtils.isEmpty(phone) ? View.VISIBLE : View.GONE);
        takeNametxt.setText(namePhone);
        takeAddress.setText(CheckUtils.isEmptyString(mOrderDetailBean.getTakeAddress()));
        transNoBtn.setVisibility(mOrderDetailBean.isEnableUpdateTransNo() ? View.VISIBLE : View.GONE);
        isEnableStockInBtn.setVisibility(mOrderDetailBean.isEnableStockIn() ? View.VISIBLE : View.GONE);
        transNo.setText(CheckUtils.isEmptyString(mOrderDetailBean.getTransNo()));/*运单号*/
        business.setText(serve);
        payState.setText(CheckUtils.isEmptyString(mOrderDetailBean.getPayStatusText()));/*支付描述*/
        int mCarriage = mOrderDetailBean.getSendCarriage() + mOrderDetailBean.getTakeCarriage();
        takeSendPrice.setText("￥" + CheckUtils.isEmptyNumber(mCarriage)); /*取送费*/
        PaymentPrice.setText("￥" + CheckUtils.isEmptyNumber(mOrderDetailBean.getPaymentPrice()));/*应收款*/
        userRemark.setText(CheckUtils.isEmptyString(mOrderDetailBean.getUserRemark()));
        if (mOrderDetailBean.getPayStatus() == 1) {  /*支付*/
            mvpPresenter.tradeOrder(orderId);
            payState.setBackgroundResource(R.drawable.shape_strok_green);
            payState.setTextColor(getColors(R.color.green));
            payStateHite.setText("已付款");
            PaymentPrice.setTextColor(getColors(R.color.green));
            PaymentPrice.setText("￥" + CheckUtils.isEmptyNumber(mOrderDetailBean.getPaidPrice()));/*已支付金额*/
            computeLayout.setVisibility(View.GONE);
            computeTop.setVisibility(View.GONE);
            computeBottom.setVisibility(View.GONE);

            signinBtn.setVisibility(isEndledSign?View.VISIBLE:View.GONE);

        } else {

            shouldPrice.setText("￥" + CheckUtils.isEmptyNumber(mOrderDetailBean.getPaymentPrice()));/*应收款*/
            gatherBtnLayout.setVisibility(mOrderDetailBean.isIsEnablePay() == true ? View.VISIBLE : View.GONE);
            gatherBtn.setVisibility(mOrderDetailBean.isIsEnablePay() == true ? View.VISIBLE : View.GONE);

            //  couponAmt.setText( mOrderDetailBean.getCouponAmt()!=0?"￥"+CheckUtils.isEmptyNumber(mOrderDetailBean.getCouponAmt()):"");
            //计价方式（1快速计价，2精准计价）
            if (isValuation) {
                preciseComputeBtn.setVisibility(View.VISIBLE);
                switch (mOrderDetailBean.getValuationType()) {
                    case 1:
                        computeLayout.setVisibility(View.VISIBLE);

                        break;
                    case 2:
                        if (!CheckUtils.isEmpty(takeName)) {
                            mOrderDetailBean.getUserInfo().setName(takeName);
                        }
                        if (!CheckUtils.isEmpty(takephone)) {
                            mOrderDetailBean.getUserInfo().setPhone(takephone);
                        }


                        break;

                }

                computePice.setText("￥" + CheckUtils.isEmptyNumber(mOrderDetailBean.getPaymentPrice()));
                computeCount.setText(mOrderDetailBean.getCreateCnt() + "");
                computeTop.setVisibility(View.VISIBLE);
            } else {
                computeTop.setVisibility(View.GONE);
            }


        }


        clototalAmount = "0";
        if (!CheckUtils.isNull(mOrderDetailBean.getValuationPrice()) || CheckUtils.isEmptyInterExist(mOrderDetailBean.getOrderPrice()) || !CheckUtils.isNull(mOrderDetailBean.getModifyPrice())) {  //下单模式 1.预约模式 2.下单支付模式
                /*计价*/
            if (!CheckUtils.isNull(mOrderDetailBean.getValuationPrice())) {
                clototalAmount=CheckUtils.isEmptyNumber(mOrderDetailBean.getValuationPrice());
            } else {
                int modifyPrice = CheckUtils.isNull(mOrderDetailBean.getModifyPrice()) ? 0 : mOrderDetailBean.getModifyPrice();
                int orderPrice = CheckUtils.isNull(mOrderDetailBean.getOrderPrice()) ? 0 : mOrderDetailBean.getOrderPrice();
                int totalPrice = orderPrice != 0 ? mOrderDetailBean.getOrderPrice() : modifyPrice;
                clototalAmount = CheckUtils.isEmptyNumber(totalPrice);

            }


        } else {
            String strtotalAmount;
            if (!CheckUtils.isEmpty(mClothlist)) {
                for (StringBean stringBean : mClothlist) {
                    String discounts = CheckUtils.isDiscount(stringBean.getDiscount());
                    String unitPrice = CheckUtils.isEmptyNumber(stringBean.getPrice());
                    if (CheckUtils.isEmpty(discounts)) {
                        strtotalAmount = DecimalUtil.multiply(stringBean.getCnt() + "", unitPrice);
                    } else {
                        String discountPrice = DecimalUtil.multiply(unitPrice, CheckUtils.isEmptyNumber(stringBean.getDiscount()));
                        strtotalAmount = DecimalUtil.multiply(stringBean.getCnt() + "", discountPrice);
                    }
                    clototalAmount = DecimalUtil.add(clototalAmount, strtotalAmount);
                }


            }



        }
        totalAmount.setText("￥" + clototalAmount);/*衣物总额*/

    }




    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_FINISG:

                gatherBtn.setVisibility(View.GONE);
                gatherBtnLayout.setVisibility(View.GONE);
                computeLayout.setVisibility(View.GONE);
                preciseComputeBtn.setVisibility(View.GONE);
                mvpPresenter.orderDetail(orderId);



                break;

        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.back_btn, gather_btn, R.id.compute_count, R.id.compute_pice, precise_compute_btn,
            receipt_btn, R.id.transNo_btn,R.id.isEnableStockIn_btn,R.id.signin_btn,R.id.call_phone_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.call_phone_layout:
                if (!CheckUtils.isEmpty(mOrderDetailBean.getTakePhone())){
                    ActivityUtils.callActivity(_mActivity,mOrderDetailBean.getTakePhone());
                }

                break;
            case  R.id.signin_btn :
            mvpPresenter.signParcel(orderId);

            break;
            case  R.id.isEnableStockIn_btn:
                if (mOrderDetailBean==null)return;
                start( StorageListFragment.createBuilder()
                        .orderId(orderId)
                        .orderNo(mOrderDetailBean.getOrderNo())
                        .isBackEnterOrderdetail(true)
                        .build());
              // startForResult(shoppingMallFragment.newInstance(true, mOrderDetailBean,true), Constant.REQUEST_CODE);
                break;
            case R.id.transNo_btn:

                  TransNoDialogFragment.createBuilder(getChildFragmentManager())
                    .orderId(orderId)
                    .mListener(mDialogSubmitListener)
                    .show();



                break;

            case receipt_btn:  /*打小票*/

               mvpPresenter.printReceipt(orderId);

                break;

            case R.id.back_btn:
                closeOtherFragment();


                break;


            case precise_compute_btn:  /*计价*/

                if (isValuation&&!CheckUtils.isNull(mOrderDetailBean)) {
                    switch (mOrderDetailBean.getValuationType()) {
                        case 1:
                            startForResult(EasyOrederFragment.newInstance(orderId, true), Constant.ClOTHING_REQUEST_CODE);
                            break;
                        case 2:
                            startForResult(shoppingMallFragment.newInstance(true, mOrderDetailBean,false), Constant.REQUEST_CODE);


                            break;
                    }
                }
                break;


            case gather_btn:  //收款
                mvpPresenter.unlockOrder(orderId);
                break;
        }
    }

    @Override
    public void loadOrderDetail(OrderDetailBean mOrderDetailBean) {
        fillData(mOrderDetailBean);

    }

    /**
     * 扣费的情况
     *
     * @param mListBean
     */
    @Override
    public void loadTradeOrder(List<TradeOrderBean.ListBean> mListBean) {
        payLayout.setVisibility(View.VISIBLE);
        if (!CheckUtils.isNull(mOrderDetailBean) && mOrderDetailBean.getCouponAmt() != 0) {
            TradeOrderBean.ListBean mItem = new TradeOrderBean.ListBean("优惠券抵扣", mOrderDetailBean.getCouponAmt());
            mListBean.add(0, mItem);

        }
        mPayListAdapter.setDataList(mListBean);
    }

    /**
     * 入库衣物清单
     */
    @Override
    public void loadProductList(List<ProductListBean> mListBean  ) {

        if (!CheckUtils.isEmpty(mListBean)) {
            enterStrongTxt.setVisibility(View.VISIBLE);
            mStorageClothingAdapter.setDataList(mListBean);
        }


    }

    /**
     * 支付信息
     *
     * @param mOrderInfoBean
     */
    @Override
    public void OrderInfoSucceed(OrderInfoBean mOrderInfoBean) {

        mOrderInfoBean.setClototalAmount(clototalAmount);
        start(PayOrderFragment.newInstance(orderId, mOrderInfoBean), SINGLETASK);
    }

    /**
     * 签收订单
     * @param msg
     */
    @Override
    public void receivingSucceed(String msg) {
        T.show(msg);
        signinBtn.setVisibility(View.GONE);
    }


    private DialogSubmitListener mDialogSubmitListener =new DialogSubmitListener() {
        @Override
        public void onSubmitClick(int parent, Object message) {
          String    strTemg=(String)message;
            switch (parent) {
                case Constant.TAG_NO:
                    if (mItem!=null){
                        mItem.setBindCode(strTemg);
                    }
                    mStorageClothingAdapter.notifyDataSetChanged();
                    break;
                case Constant.TRANS_NO:
                    transNo.setText(strTemg);

                    break;
            }
        }
    };
    @Override
    public boolean onBackPressedSupport() {
        closeOtherFragment();

        return true;
    }

    private void closeOtherFragment() {

        if ( isAdded()&&findFragment(OrderdetailFragment.class)!=null) {
            if (isPopToHome) {

                popTo(HomeFragment.class, false);
            } else {
                finish();
            }
        }
    }


    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {

        if (CheckUtils.isMIUIDevices()){
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(), mReceiptBean);
        }else{
            BluetoothPrintHelper.receiptReceipt(_mActivity,mReceiptBean);
        }

    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.ClOTHING_REQUEST_CODE:
                case Constant.REQUEST_CODE:
                    mvpPresenter.orderDetail(orderId);

                    break;
            }
        }
    }



}
